package playn101.core;

import static playn.core.PlayN.*;

import playn.core.*;

public class PlayN101 implements Game {
  int current = 0;
  Game[] games = {
    new A(),
    new B(),
    new C(),
    new D(),
    new E(),
    new F(),
    new G(),
    new H(),
    new I(),
    new J()
  };

  ImageLayer bgLayer;
  boolean calledInitGame = false;
  
  @Override
  public void init() {
    // Preload all assets and only init the game when the assets are all loaded
    String[] allAssets = new String[]{"ball.png", "block.png", "cloud.png", "font.png", "pin.png"};
    AssetWatcher watcher = new AssetWatcher(new AssetWatcher.Listener() {
      public void done() {
        startGame();
      }
      public void error(Throwable e) {
        e.printStackTrace();
      }
    });
    for (String imageName : allAssets) {
        watcher.add(assetManager().getImage("images/" + imageName));
    }
    watcher.start();
  }
  
  private void startGame() {
    calledInitGame = true;
    games[current].init();
    keyboard().setListener(new Keyboard.Adapter() {
	public void onKeyDown(Keyboard.Event event) {
	  int keyCode = event.key().ordinal() - Key.K1.ordinal();
	  setCurrentGame(keyCode);  
	}
      });
  }

  public void setCurrentGame(int game) {
    if (game >=0 && game < games.length) {
      current = game;
      graphics().rootLayer().clear();
      games[current].init();
    }
  }

  @Override
  public void paint(float delta) {  
    if (!calledInitGame) {
      return;
    }
    // the background automatically paints itself, so no need to do anything here!
    games[current].paint(delta);
  }

  @Override
  public void update(float delta) {
    if (!calledInitGame) {
      return;
    }
    games[current].update(delta);
  }

  @Override
  public int updateRate() {
    return 25;
  }
}
